<template>
  <div class="_wz_sendNoticeAdd">
    <Steps :current="current" style="width: 80%;margin: auto;">
      <Step title="基本信息"></Step>
      <Step title="企业选择"></Step>
      <Step title="人员选择"></Step>
      <Step title="信息展示"></Step>
    </Steps>
    <div style="height: 100%;overflow: auto;">
      <div v-show="current == 0" style="padding: 10px;">
        <Form ref="formAdd" :model="formData" label-position="right" :label-width="110" :rules="ruleValidate">
          <FormItem label="通知标题" prop="noticeTitle">
            <i-input v-model="formData.noticeTitle" placeholder="请填写通知标题" clearable />
          </FormItem>

          <Row>
            <Col span="8">
            <FormItem label="通知等级" prop="noticeLv">
              <i-select v-model.number="formData.noticeLv" filterable placeholder="请选择通知等级" clearable>
                <Option :value="1">普通</Option>
                <Option :value="2">重要</Option>
                <Option :value="3">紧急</Option>
              </i-select>
            </FormItem>
            </Col>
            <Col span="16">
            <FormItem label="通知人员" prop="orgContact">
              <i-input v-model="formData.orgContact" placeholder="请填写通知人员" clearable />
            </FormItem>
            </Col>
          </Row>

          <Row style="height: 58px;">
            <Col span="8">
            <FormItem label="文件下发" prop="noticeFileType">
              <i-switch v-model.number="formData.noticeFileType" :false-value="0" :true-value="1">
                <template #open><span>开</span></template>
                <template #close><span>关</span></template>
              </i-switch>
            </FormItem>
            </Col>
            <Col span="16" v-if="formData.noticeFileType">
            <FormItem label="通知附件" prop="multipartFile">
              <Upload name="multipartFile" :before-upload="handleUpload" action="" style="display: inline-block;">
                <Button type="primary" icon="ios-cloud-upload-outline">上传附件(仅支持mp4、docx)</Button>
                {{ fileData.name }}
              </Upload>
              <Button type="primary" icon="md-cloud-download" v-if="!!formData.noticeFileUrl && !fileData.name"
                style="margin: 0 0 0 10px;" @click="dateienHerunterladen">下载文件</Button>
            </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="8">
            <FormItem label="回复状态" prop="noticeReplyType">
              <i-switch v-model.number="formData.noticeReplyType" :false-value="0" :true-value="1">
                <template #open><span>开</span></template>
                <template #close><span>关</span></template>
              </i-switch>
            </FormItem>
            </Col>
            <Col span="16" v-if="formData.noticeReplyType">
            <FormItem label="回复时间" prop="noticeEndTime">
              <DatePicker type="datetime" v-model="formData.noticeEndTime" show-week-numbers placeholder="请选择回复时间" />
            </FormItem>
            </Col>
          </Row>
          <FormItem label="通知内容" prop="noticeContent">
            <div style="border: 1px solid #ccc;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                :defaultConfig="{ excludeKeys: ['insertLink', 'group-image', 'fullScreen', 'group-video'] }"
                mode='default' />
              <Editor style="height: 500px; overflow-y: hidden;" v-model="formData.noticeContent"
                :defaultConfig="{ placeholder: '请输入内容...' }" mode='default' @onCreated="handleCreated" />
            </div>
          </FormItem>
        </Form>
      </div>
      <div v-show="current == 1" style="padding: 10px;height: 100%;" class="_wz_sendNoticeAdd_tbale">


        <Form :model="formData" label-position="right" :label-width="120">
          <FormItem label="运输类型" class="ivu-form-item-required">
            <CheckboxGroup v-model="formData.noticePublishDeptType">
              <Checkbox v-for="item in transportTypeList" :label="item.code" :key="item.code">{{ item.value }}</Checkbox>
            </CheckboxGroup>
          </FormItem>
        </Form>
        <div style="height: 100%;overflow: auto;">
          <!-- <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale> -->
          <wzTbale ref="wzTbale" :formData="formData" @listenSonCompany="listenSonCompany"></wzTbale>
        </div>
      </div>
      <div v-show="current == 2" style="padding: 10px;height: 100%;" class="_wz_sendNoticeAdd_tbale">


        <Row>
          <Col span="4"> 发布类型</Col>
          <Col span="18">
          <RadioGroup v-model="formData.noticePublishType" type="button">
            <Radio label="0">按从业类型</Radio>
            <Radio label="1">按从业人员</Radio>
          </RadioGroup>
          </Col>
        </Row>
        <br>
        <Row>
          <Col span="4">从业人员类型</Col>
          <Col span="18 ">
          <CheckboxGroup v-model="formData.noticePublishValueCode" @on-change="noticePublishValueCodeOnChange">
            <Checkbox v-for="item in personTypeList" :label="item.code" :key="item.code">{{ item.value }}</Checkbox>
          </CheckboxGroup>
          </Col>
        </Row>

        <div style="height: 100%;overflow: auto;" v-if="formData.noticePublishType == 1">
          <wttTbale :formData="formData" @listenSonCompanyDrive="listenSonCompanyDrive"
            :TableDataCompany="TableDataCompany"></wttTbale>

        </div>





      </div>
      <div v-show="current == 3" class="_wz_sendNoticeAdd_tbale">
        <tableDataShow :tableDataProp="formData" />

        <div class="ul">
          <Table :columns="tableData.columnsTable" :data="TableDataCompanyDrive"></Table>
        </div>

      </div>
    </div>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" type="primary" @click="addSubmit" v-if="current == 3">提交</Button>
      <Button style="margin-right: 8px" type="primary" v-if="current != 0" @click="Previous">上一步</Button>
      <Button style="margin-right: 8px" type="primary" v-if="current != 3" @click="nextFun">下一步</Button>
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
    </div>
  </div>
</template>
<script>


import { shallowRef, getCurrentInstance, inject, nextTick, reactive, toRefs, toRef, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, ref, defineComponent, toRaw, watch } from 'vue'
import { useRouter, useRoute } from "vue-router";

import { useMainStore } from '../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex
import tableDataShow from "./tableDataShow.vue";

import wzTbale from "../../components/table/companyTable.vue";
import wttTbale from "../../components/table/companyDriveTable.vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { systemDictList } from "@/util/commonInterfaces";

//reactive
export default defineComponent({
  name: 'sendNoticeAdd',//组件名称
  components: {
    Editor, Toolbar,
    wzTbale, wttTbale, tableDataShow
  },//组件引用
  props: ['selectData'],//接收来自父组件的数据
  setup(props, context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $common = inject('$common');//自己封装的方法


    // 用于获取$refs
    const formAdd = ref();
    const wzTbale = ref();
    let listenSonCompanyList = ref();  //选择的企业数据
    let TableDataCompany = ref([]);  //表格展示的企业数据

    let listenSonCompanyDriveList = ref() //选择的企业下的人员数据
    let TableDataCompanyDrive = ref([]);  //表格展示的企业下的人员数据



    const state = reactive({
      transportTypeList: [],//运输类型
      personTypeList: [],// 从业人员类型
      current: 0,//当前状态
      formData: {
        noticeFileType: 1,
        noticeReplyType: 1,
        noticeEndTime: new Date(),
        noticePublishType: "1"
      },//表单数据
      ruleValidate: {//表单正则
        noticeTitle: [
          { required: true, message: "请填写通知标题", trigger: "blur" }
        ],
        noticeLv: [
          { type: 'number', required: true, message: "请选择通知等级", trigger: "blur" }
        ],
        orgContact: [
          { required: true, message: "请填写通知人员", trigger: "blur" }
        ],
        noticeEndTime: [
          { type: 'date', required: true, message: "请选择回复时间", trigger: "blur" }
        ],
      },
      fileData: {
        data: null,
        name: '',
      },

      tableData: {
        height: "100%", //表格高度 auto
        page: false, //分页是否使用
        columns: [
          //表头数据
          { type: "selection", width: 70, align: "center" },
          { type: "index", width: 70, align: "center", title: "序号" },
          { title: '经营企业', minWidth: 210, key: 'deptName', tooltip: true, resizable: true, },
          { title: '经营类型', minWidth: 120, key: 'transportValue', tooltip: true, resizable: true, },
          { title: '法人代表', minWidth: 120, key: 'legalPerson', tooltip: true, resizable: true, },
          { title: '经营负责人', minWidth: 120, key: 'personCharge', tooltip: true, resizable: true, },
          { title: '负责人电话', minWidth: 120, key: 'personChargePhone', tooltip: true, resizable: true, },
          { title: '营业执照号', minWidth: 180, key: 'uniformSocialCreditCode', tooltip: true, resizable: true, },
        ],
        columnsTable: [
          { title: '人员名称', minWidth: 10, key: 'name', tooltip: true, resizable: true, },
          { title: '从业类型', minWidth: 10, key: 'deptTypeName', tooltip: true, resizable: true, },
          { title: '运输企业', minWidth: 150, key: 'deptName', tooltip: true, resizable: true, },
          { title: '手机号', minWidth: 120, key: 'phone', tooltip: true, resizable: true, },
        ],
        dataList: []
      }


    });

    //监听

    //监听

    // watch(() => state.formData.noticePublishValueCode, (news, old) => {
    //   if (state.formData.noticePublishValueCode.length > 0) {
    //     studentTypeFun();
    //   } else {
    //     state.tableData.dataList = [];
    //     $ViewUIPlus.Message.error('请至少选择一个运输类型');
    //   }
    // }, { deep: true });




    //编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    // 记录 editor 实例，重要！
    const handleCreated = (editor) => {
      editorRef.value = editor
    }




    //文件上传
    const handleUpload = (file) => {
      let type = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (type == "MP4" || type == "mp4") {//视频
        state.formData.noticeFileType = 1;
        state.fileData.data = file;
        state.fileData.name = file.name;
      } else if (type == "DOCX" || type == "docx") {//word
        state.formData.noticeFileType = 2;
        state.fileData.data = file;
        state.fileData.name = file.name;
      } else {
        $ViewUIPlus.Message.error('您上传的文件类型不匹配');
        return false;
      }
      return false;
    }


    //上一步
    const Previous = () => {
      if (state.current == 0) {
        return false;
      } else {
        state.current = state.current - 1;
      }
    }

    //下一步
    const nextFun = () => {
      if (state.current == 0) {
        formAdd.value.validate(async (valid) => {
          if (valid) {
            state.current = state.current + 1;
            studentTypeFun();
          } else {
            $ViewUIPlus.Message.error('请正确填写表单');
          }
        })
      } else if (state.current == 1) {//判断是否选择企业
        state.current = state.current + 1;
      } else if (state.current == 2) {//判断是否选择人员
        state.current = state.current + 1;
      }

    }


    //监听子组件选择的企业数据  这个子组件 ../../components/table/companyTable.vue
    const listenSonCompany = (data) => {
      console.log("companyTable选择的企业数据", data)

      listenSonCompanyList.value = data

      let listarr = []
      for (let item in listenSonCompanyList.value) {
        listarr.push(...listenSonCompanyList.value[item])
      }

      TableDataCompany.value = listarr
    }
    //监听子组件选择的人员的数据  这个子组件 ../../components/table/companyDriveTable.vue
    let listenSonCompanyDrive = (data) => {
      console.log("选择的人员数据", data)

      listenSonCompanyDriveList.value = data

      let listarr = []
      for (let item in listenSonCompanyDriveList.value) {
        listarr.push(...listenSonCompanyDriveList.value[item])
      }

      TableDataCompanyDrive.value = listarr  //表格展示的企业下的人员数据
    }


    //提交
    const addSubmit = () => {


      let data = JSON.parse(JSON.stringify(state.formData));
      console.log(data)

      let formData = new FormData();





      let tableDataCompanyList = TableDataCompany.value; //选中的企业
      let noticePublishDeptValue = [];  //要保存的企业的名称uuid
      for (let key in tableDataCompanyList) {
        noticePublishDeptValue.push(tableDataCompanyList[key].uuid)
      }
      data.noticePublishDeptValue = noticePublishDeptValue.toString();


      let TableDataCompanyDriveList = TableDataCompanyDrive.value; //选中的企业下的人
      let noticePublishDriverValue = [];  //要保存的从业人员的的UUID
      for (let key in TableDataCompanyDriveList) {
        noticePublishDriverValue.push(TableDataCompanyDriveList[key].uuid)
      }
      data.noticePublishDriverValue = noticePublishDriverValue.toString();



      if (data.noticePublishType == '0') {  //发布类型是根据就业类型来的话那么就业人员就是空的
        data.noticePublishDriverValue = ""
      }

      //处理 回复时间
      // if (!data.noticeReplyType) {
      //   delete data.noticeEndTime;
      // } else {
      //   //时间处理转换
      //   data.noticeEndTime = $common.timeFormatting(new Date(data.noticeEndTime), 'yyyy-MM-dd hh:mm:ss')
      // }

      //处理文件
      if (!!data.noticeFileType && state.fileData.data) {
        formData.append("multipartFile", state.fileData.data);
      }





      for (let key in data) {

        formData.append(key, data[key]);
      }

      console.log("要提交的数据", data)


      $axios.post(apiUrl.noticeDeptMessageNoticeDeptMessageSaveOrUpdate, formData).then((res) => {
        if (res.data.code == 0) {
          $ViewUIPlus.Message.success('保存成功');
          context.emit('closeFun', true)
        } else {
          $ViewUIPlus.Message.error('保存失败');
        }
      }).catch((err) => {
        console.log("失败", err)
      })



    }

    //类型发生变化  加载表格数据
    const studentTypeFun = () => {
      // $axios.post(apiUrl.coreDeptCoreDeptList, { transportCodeList: state.formData.noticePublishValueCode }).then((res) => {

      //   if (!!props.selectData.id) {//修改
      //     if (!!state.formData.noticePublishDeptValue) {
      //       res.data.data.forEach(function (k, i) {
      //         state.formData.noticePublishDeptValue.forEach(function (ko, io) {
      //           if (k.uuid == ko) {
      //             k._checked = true;
      //           }
      //         });
      //       });
      //     }
      //   }



      //   state.tableData.dataList = res.data.data;
      // }).catch((err) => {
      //   console.log("失败", err)
      // })

    }

    //下载文件
    const dateienHerunterladen = () => {
      window.open(apiUrl.export + state.formData.noticeFileUrl)
    }

    let noticePublishValueCodeOnChange = (arr) => {
      console.log(arr)
    }


    // 其他的生命周期
    onBeforeMount(() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted(async () => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")

      state.transportTypeList = await systemDictList({ type: 'transport_type' })  //运输类型
      state.personTypeList = await systemDictList({ type: 'person_type' })  //从业人员类型




      if (!!props.selectData.id) {//修改
        // $axios.post(apiUrl.noticeOrgMessageNoticeOrgMessageInfo, { uuid: props.selectData.uuid }).then((res) => {
        //   let formData = res.data.data;
        //   formData.noticePublishValueCode = formData.noticePublishValueCode.split(',')
        //   //表格
        //   formData.noticePublishDeptValue = formData.noticePublishDeptValue.split(',')

        // props.selectData.noticePublishValueCode = props.selectData.noticePublishValueCode.split(",")
        // props.selectData.noticePublishDeptValue = props.selectData.noticePublishDeptValue.split(",")

        state.formData = props.selectData;

        //   console.log(state.formData)
        // }).catch((err) => {
        //   console.log("失败", err)
        // })





      } else {//添加

        //运输类型
        let transportTypeList = [];
        state.transportTypeList.map((k, i) => {
          transportTypeList.push(k.code)
        })
        state.formData.noticePublishDeptType = transportTypeList;



        //从业人员类型
        let personTypeList = [];
        state.personTypeList.map((k, i) => {
          personTypeList.push(k.code)
        })
        state.formData.noticePublishValueCode = personTypeList;


      }


    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate(() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated(() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount(() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted(() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      handleUpload,//通知附件
      Previous,//上一步
      nextFun,//下一步
      addSubmit,//提交
      formAdd,//用于表单验证使用
      studentTypeFun,//类型发生变化  加载表格数据
      dateienHerunterladen,//下载文件

      wzTbale,//表格 调用
      editorRef,//编辑器实例，必须用 shallowRef
      handleCreated,//记录 editor 实例，重要！
      listenSonCompany, //获取列表中的选中的企业的监听方法
      listenSonCompanyList,  //子组件的方法企业
      noticePublishValueCodeOnChange, //从业人员类型改变重新获取人员数据
      TableDataCompany,
      listenSonCompanyDrive,  //子组件监听的方法企业下的人员
      TableDataCompanyDrive
    }
  }
})


</script>
<style lang="less">
._wz_sendNoticeAdd {
  height: 100%;
  display: flex;
  flex-direction: column;

  ._wz_sendNoticeAdd_tbale {

    height: 100%;
    display: flex;
    flex-direction: column;
  }
}
</style>
